package com.lgd.factoryattendance.Activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONObject;
import com.lgd.factoryattendance.Bean.WorkHourStatistics;
import com.lgd.factoryattendance.R;
import com.lgd.factoryattendance.Utils.ScreenUtils;
import com.lgd.factoryattendance.Utils.ToastUtils;
import com.lgd.factoryattendance.View.TextConfigNumberPicker;
import com.lgd.factoryattendance.httpService.API;
import com.lgd.factoryattendance.httpService.httpPort.IStringResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class AdminActivity extends AppCompatActivity implements View.OnClickListener {
    LinearLayout durationInfo_layout,assembly_layout,layout_electricPDF,layout_back, Guide_PDF_layout;
    Long userId;
//    PDFView pdfView;
    public static final String SYSTEM_DIALOG_REASON_KEY = "reason";
    public static final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
    private HomeWatcherReceiver mHomeKeyReceiver;
    ImageView iv_jia, iv_bom_list;
    PopupWindow menu_pop;
    private static final String TAG = "AdminActivity";
//    private AudioManager audioManager;
//    Button btn_logout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin);
        init();
//        registerHomeKey(getApplicationContext());//监听 home键
    }

    public void init(){
        Intent intent = getIntent();
        userId = intent.getLongExtra("userId",0);
        System.out.println("--- userid ----"+userId);
        durationInfo_layout = findViewById(R.id.durationInfo_layout);
        durationInfo_layout.setOnClickListener(this);
        assembly_layout = findViewById(R.id.assembly_layout);
        assembly_layout.setOnClickListener(this);
        layout_electricPDF = findViewById(R.id.layout_electricPDF);
        layout_electricPDF.setOnClickListener(this);
        layout_back = findViewById(R.id.layout_back);
        layout_back.setOnClickListener(this);
        iv_jia = findViewById(R.id.iv_jia);
        iv_jia.setOnClickListener(this);
        menu_pop = new PopupWindow(getApplicationContext());
        Guide_PDF_layout = findViewById(R.id.Guide_PDF_layout);
        Guide_PDF_layout.setOnClickListener(this);
        iv_bom_list = findViewById(R.id.iv_bom_list);
        iv_bom_list.setOnClickListener(this);
//        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.durationInfo_layout:
                popDurationInfo();
                setAlpha(0.5f);
                durationInfo_pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        setAlpha(1.0f);
                    }
                });
                break;
            case R.id.assembly_layout:  // 部装
                startActivity(new Intent(AdminActivity.this,UnitInfoActivity.class));
                break;
            case R.id.layout_electricPDF:
                 startActivity(new Intent(AdminActivity.this,ElectricGalleryActivity.class));
                break;
            case R.id.layout_back:
                finish();
                break;
            case R.id.iv_jia:
                menuPopupwindow();
                break;
            case R.id.Guide_PDF_layout:
//                startActivity(new Intent(AdminActivity.this,Guide_PDF_Activity.class));
                startActivity(new Intent(AdminActivity.this, PDF_Search_Activity.class));
                break;
            case R.id.iv_bom_list:
                startActivity(new Intent(AdminActivity.this, BomListInfoActivity.class));
                break;
            default:
                break;
        }
    }


    //  目录 弹窗
    public void menuPopupwindow(){
        // 设置布局文件
        menu_pop.setContentView(LayoutInflater.from(this).inflate(R.layout.admin_menu_pop, null));
        menu_pop.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        menu_pop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        menu_pop.setBackgroundDrawable(new ColorDrawable(0x0000));
        menu_pop.setFocusable(true);
        menu_pop.setTouchable(true);
        menu_pop.setOutsideTouchable(true);
        menu_pop.showAsDropDown(iv_jia, -20, 0);
        menu_pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setAlpha(1.0f);
            }
        });
        TextView tv_volume = menu_pop.getContentView().findViewById(R.id.tv_volume);
        tv_volume.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menu_pop.dismiss();
//                showDialog();
                setVolumeBrightnessPop();
            }
        });
    }

    //  音量和亮度 弹窗
    PopupWindow volume_bright_pop;
    public void setVolumeBrightnessPop(){
        View volume_bright_view = getLayoutInflater().inflate(R.layout.dialog_out_layout,null);
        int width = ScreenUtils.getWidth(getApplicationContext());
//        volume_bright_pop = new PopupWindow
//                (volume_bright_view, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        volume_bright_pop = new PopupWindow
                (volume_bright_view, width * 8/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        volume_bright_pop.setTouchable(true);
        volume_bright_pop.setFocusable(true);
        volume_bright_pop.setOutsideTouchable(true);
        volume_bright_pop.setBackgroundDrawable(new ColorDrawable(0x0000));
        volume_bright_pop.showAtLocation(AdminActivity.this.getWindow().getDecorView(), Gravity.CENTER,0,0);
    }

    //   音量dailog弹窗
//    public void showDialog() {
//        AlertDialog.Builder builder = new AlertDialog.Builder(AdminActivity.this);
//        View view = View.inflate(AdminActivity.this, R.layout.dialog_out_layout, null);
//        builder.setView(view);
//        builder.setCancelable(true);
//        TextView title = (TextView) view.findViewById(R.id.title); // 设置标题
//        // 注意：如果您需要设置标题，您可能还需要调用 builder.setTitle(...) 或者直接设置 title 文本的文本内容
//        EditText input_edt = (EditText) view.findViewById(R.id.dialog_edit); // 输入内容
//        Button btn_volume_down = (Button) view.findViewById(R.id.btn_volume_down); // -
//        Button btn_volume_plus = (Button) view.findViewById(R.id.btn_volume_plus); // +
//        // 设置按钮的点击事件监听器
//        btn_volume_down.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                decreaseVolume();
//            }
//        });
//        btn_volume_plus.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                increaseVolume();
//            }
//        });
//        // 创建对话框
//        AlertDialog dialog = builder.create();
//        // 设置对话框窗口的背景为透明
//        Window window = dialog.getWindow();
//        if (window != null) {
//            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//        }
//        // 显示对话框
//        dialog.show();
//    }

    // 增加音量的方法
//    private void increaseVolume() {
//        int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
//        int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//        if (currentVolume < maxVolume) {
//            audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
//        }
//    }
    // 减少音量的方法
//    private void decreaseVolume() {
//        int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
//        if (currentVolume > 0) {
//            audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
//        }
//    }

    // dialog 查看 PDF
    private void showPdfInDialog(String fileName) {
        Dialog dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_pdf_viewer);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent); // 设置Dialog背景透明
        dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT); // 设置Dialog大小
        dialog.show();
//        PDFView pdfView = dialog.findViewById(R.id.pdfView);
////        pdfView.setOffscreenPageLimit(3);
//        pdfView.isCanZoom(true);
//        pdfView.setMaxScale(10f);
//        pdfView.showPdfFromUrl(fileName);
    }
    // 本月 时长弹窗
    PopupWindow durationInfo_pop;
    TextView selectMonth_TV;
    TextView DurationMonth_TV;
    public void popDurationInfo(){
        View durationInfo_view = getLayoutInflater().inflate(R.layout.duration_info, null);
        int width = ScreenUtils.getWidth(AdminActivity.this);
        durationInfo_pop = new PopupWindow
                (durationInfo_view, width * 9/10, ViewGroup.LayoutParams.WRAP_CONTENT);
        durationInfo_pop.setTouchable(true);
        durationInfo_pop.setFocusable(true);
        durationInfo_pop.setOutsideTouchable(true);
        durationInfo_pop.setBackgroundDrawable(new ColorDrawable(0x0000));

//        Spinner staffTime_SP = durationInfo_view.findViewById(R.id.staffTime_SP);
        selectMonth_TV = durationInfo_view.findViewById(R.id.selectMonth_TV);
        DurationMonth_TV = durationInfo_view.findViewById(R.id.DurationMonth_TV);
        LinearLayout selectMonth_layout = durationInfo_view.findViewById(R.id.selectMonth_layout);
        selectMonth_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setData();
            }
        });
        Button queryDuration_BT = durationInfo_view.findViewById(R.id.queryDuration_BT);
        queryDuration_BT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (userId == 0){
                    ToastUtils.warnShowLong(getApplicationContext(),"请先刷卡，再进行查询！");
                }else {
                    WorkHourStatistics w = new WorkHourStatistics();
                    w.setUserid(userId);
                    w.setProducedate(selectMonth_TV.getText().toString());
                    selectDurationList(w);
                }
            }
        });
        durationInfo_pop.showAtLocation(AdminActivity.this.getWindow().getDecorView(),Gravity.CENTER,0,0);
    }
    // 查询 时长
    public void selectDurationList(WorkHourStatistics w){
        API.selectDurationList(w, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                JSONObject j = JSONObject.parseObject(result);
                AdminActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        DurationMonth_TV.setText(j.getString("data"));
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    // 设置 年月 选择弹框控件
    public void setData(){
        // 加载自定义布局
        View view = LayoutInflater.from(AdminActivity.this).inflate(R.layout.dialog_date_picker, null);
        final TextConfigNumberPicker yearPicker = view.findViewById(R.id.yearPicker);
        final TextConfigNumberPicker monthPicker = view.findViewById(R.id.monthPicker);
        final Button Ok_BT = view.findViewById(R.id.Ok_BT);
        final Button Cancel_BT = view.findViewById(R.id.Cancel_BT);
        // 设置年份范围
        final int curYear = Calendar.getInstance().get(Calendar.YEAR);
        yearPicker.setMinValue(curYear);
        yearPicker.setMaxValue(curYear + 15);
        // 设置月份范围
        String[] months = new String[]{"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"};
        monthPicker.setDisplayedValues(months);
        monthPicker.setMinValue(0);
        monthPicker.setMaxValue(11);

        yearPicker.setMInputStyle(16f);
        monthPicker.setMInputStyle(16f);
        // 设置滚动监听器
        yearPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                picker.performClick();  //刷新选中状态
                int year = picker.getValue();
                int month = monthPicker.getValue() + 1; // 加1是因为数组下标从0开始
                Log.d(TAG, "Selected year: " + year + ", month: " + month);
            }
        });
        monthPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                picker.performClick();
                int year = yearPicker.getValue();
                int month = picker.getValue() + 1; // 加1是因为数组下标从0开始
//                Log.d("TAG", "Selected year: " + year + ", month: " + month);
            }
        });
        // 构建AlertDialog
        AlertDialog.Builder builder = new AlertDialog.Builder(AdminActivity.this);
        builder.setTitle("请选择年月");
        builder.setView(view);
        AlertDialog alertDialog = builder.create();
        Ok_BT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int year = yearPicker.getValue();
                int month = monthPicker.getValue() + 1; // 加1是因为数组下标从0开始
                StringBuilder sb = new StringBuilder();
                sb.append(year).append("-").append(month);
                String str = timeConvert(sb.toString());
                selectMonth_TV.setText(str);
                alertDialog.dismiss();
            }
        });
        Cancel_BT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });

        alertDialog.show();
    }
    // 时间格式转换
    public String timeConvert(String time){
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-M");
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM");
        String time_str = null;
        try {
            Date date = inputFormat.parse(time);
            String formattedDate = outputFormat.format(date);
            time_str = formattedDate;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time_str;
    }
    //    遮罩层
    private void setAlpha(float f) {
        WindowManager.LayoutParams lp =getWindow().getAttributes();
        lp.alpha = f;
        getWindow().setAttributes(lp);
    }
    // 监听 home 返回    方法一
    public void registerHomeKey(Context context){
        //注册Home监听广播
        mHomeKeyReceiver = new HomeWatcherReceiver();
        final IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        context.registerReceiver(mHomeKeyReceiver, homeFilter);
    }

    private static class HomeWatcherReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
                if (SYSTEM_DIALOG_REASON_HOME_KEY.equals(reason)) {
                    System.out.println("--------监听home 返回键 -----------");
                }
            }
        }
    }
//      方法 二
//    @Override
//    protected void onUserLeaveHint() {
//        super.onUserLeaveHint();
//        System.out.println("-----  点击 返回桌面-------");
//
//    }

    private void finishApp(){
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }


}